import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mathfun/features/training_records/bloc/training_history_event.dart';
import '../features/training_records/bloc/training_history_bloc.dart';
import '../features/training_records/model/training_record.dart';
import '../features/training_records/bloc/training_history_state.dart';
import 'package:intl/intl.dart';

class TrainingHistoryPage extends StatefulWidget {
  const TrainingHistoryPage({super.key});

  @override
  State<TrainingHistoryPage> createState() => _TrainingHistoryPageState();
}

class _TrainingHistoryPageState extends State<TrainingHistoryPage> {
  @override
  void initState() {
    super.initState();
    context.read<TrainingHistoryBloc>().add(const TrainingHistoryLoaded());
  }

  String _getTrainingTypeName(String type) {
    switch (type) {
      case 'dot':
        return '点数训练';
      case 'dot_flash':
        return '点数快闪训练';
      case 'audio':
        return '听算训练';
      case 'make_ten':
        return '凑十训练';
      default:
        return '未知训练';
    }
  }

  Color _getTrainingTypeColor(String type) {
    switch (type) {
      case 'dot':
        return Colors.blue;
      case 'audio':
        return Colors.green;
      case 'make_ten':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('训练记录'),
        actions: [
          IconButton(
            icon: const Icon(Icons.delete_sweep),
            onPressed: () => _showClearConfirmationDialog(context),
          ),
        ],
      ),
      body: BlocBuilder<TrainingHistoryBloc, TrainingHistoryState>(
        builder: (context, state) {
          print('Training history state: ${state.runtimeType}');
          if (state is TrainingHistoryLoading) {
            print('Loading training records...');
            return const Center(child: CircularProgressIndicator());
          }
          if (state is TrainingHistoryError) {
            print('Error loading records: ${state.message}');
            return Center(child: Text('加载失败: ${state.message}'));
          }
          if (state is TrainingHistoryLoadedSuccess) {
            final records = state.records;
            print('Loaded ${records.length} training records for display');
            if (records.isEmpty) {
              print('No records found in TrainingHistoryLoadedSuccess state');
              return const Center(
                child: Text('暂无训练记录'),
              );
            }
            return ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: records.length,
              itemBuilder: (context, index) {
                final record = records[index];
                return Card(
                  elevation: 2,
                  margin: const EdgeInsets.only(bottom: 12),
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children:
                      [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children:
                          [
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 4,
                              ),
                              decoration: BoxDecoration(
                                color: _getTrainingTypeColor(record.type),
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: Text(
                                _getTrainingTypeName(record.type),
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                            Text(DateFormat('yyyy-MM-dd HH:mm').format(record.timestamp)),
                          ],
                        ),
                        const SizedBox(height: 12),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children:
                          [
                            _buildStatItem('正确率', '${(record.accuracy * 100).toStringAsFixed(1)}%'),
                            _buildStatItem('用时', record.formattedDuration),
                            _buildStatItem('得分', '${record.correctCount}/${record.totalCount}'),
                          ],
                        ),
                      ],
                    ),
                  ),
                );
              },
            );
          }
          return const Center(child: Text('未知状态'));
        },
      ),
    );
  }

  Widget _buildStatItem(String label, String value) {
    return Column(
      children:
      [
        Text(
          label,
          style: const TextStyle(
            color: Colors.grey,
            fontSize: 12,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
      ],
    );
  }

  void _showClearConfirmationDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认清除'),
        content: const Text('确定要清除所有训练记录吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              context.read<TrainingHistoryBloc>().add(const TrainingRecordsCleared());
            },
            child: const Text('清除'),
          ),
        ],
      ),
    );
  }
}